﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.NewsLetters.Models;
using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.NewsLetters.Services
{
	public class DBContactRecipientSourceProvider : UserRecipientSourceProviderBase
	{
		public DBContactRecipientSourceProvider(
			ERPStore.Services.IValidatorService validator
			, NewsLettersService newsLetterService
			, ERPStore.Logging.ILogger logger)
			: base(validator, newsLetterService, logger)
		{
		}

		#region IRecipientListProvider Members

		public override void Initialize(Models.EmailListSource source)
		{
			if (source == null)
			{
				throw new ArgumentException("source does not be null");
			}
			if (source.Settings.IsNullOrEmpty())
			{
				m_Filter = new ERPStore.Models.UserListFilter();
			}
			else
			{
				var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ERPStore.Models.UserListFilter));
				var buffer = System.Text.Encoding.UTF8.GetBytes(source.Settings);
				using (var ms = new System.IO.MemoryStream(buffer))
				{
					m_Filter = (ERPStore.Models.UserListFilter)serializer.Deserialize(ms);
					ms.Flush();
					ms.Close();
				}
			}
		}

		public override string SourceTypeId
		{
			get { return "FADC0FCB-488A-448B-8AC1-96FB986AF6D8"; }
		}

		public override string DisplayName
		{
			get
			{
				return "Contacts filtrés";
			}
		}

		public override IList<ERPStore.Models.BrokenRule> Validate()
		{
			return ValidatorService.Validate(this.m_Filter);
		}

		public override string GetSerializedSettings()
		{
			return m_Filter.SerializeToXml();
		}

		#endregion
	}
}
